RAILS_ENV = 'development'
require File.dirname(__FILE__) + "/../config/environment"
require 'jcode'
$KCODE = 'u'

def strip_last_name(name)
  name.gsub(/(ai|as|ą|čiui|čio|is|io|į|iuj|iu|iaus|iui|ius|ių|iumi|os|iaus|o|u|ui|ys)$/, '').gsub(/(|ė|ės|ei|e|ę|a)$/, '')
end

def capitalize_name(name)
  c_name = ''
  index = 1
  name.each_char{ |char|
    n =  index == 1 ? char : char.downcase.tr("ĄČĘĖĮŠŲŪŽ","ąčęėįšųūž")
    c_name += n
    index += 1
  }
  c_name
end

authors = Hash.new

IO.readlines("stenogramos").each do |line|
  m = line.match(/^\D\.(\D\.)?\w+/)
  if m then
    speeker = m.to_s.split('.')
    speeker_first_name_initial = speeker.first
    speeker_last_name = capitalize_name(speeker.last)
    author_sql =<<-SQL
    select
      *
    from politicians
    where
      last_name = '#{speeker_last_name}' and
      (substring(first_name, 1,1) = '#{speeker_first_name_initial}' or substring(second_name, 1,1) = '#{speeker_first_name_initial}')
    SQL
    mp = Politician.find_by_sql(author_sql).first
    if mp then
      authors[mp] ||= Hash.new
      references = authors[mp]
      speech = line.sub m.to_s, ''
      speech.scan( /( \D\.(\D\.)?\w+)/ ).each do |mp|
        name = strip_last_name mp[0].strip
        first_name_initials = name.split('.').first
        last_name = name.split('.').last
        reference_sql=<<-SQL
        select 
          *
        from politicians 
        where 
          last_name like '#{last_name + '%'}' and
          (substring(first_name, 1,1) = '#{first_name_initials}' or substring(second_name, 1,1) = '#{first_name_initials}')
        SQL
        ref_mp = Politician.find_by_sql(reference_sql).first
        if ref_mp then
          references[ref_mp] = references[ref_mp] ? references[ref_mp] + 1 : 1
        else
          #printf "nera #{first_name_initials}, #{last_name}\n"
        end
      end
    end
  end
end

authors.each do |mp, speech|
  printf "#{mp.full_name}\n"
  speech.sort{|x,y| y[1] <=> x[1]}.each do |ref, count|
    printf "\t#{ref.full_name} - #{count}\n"
  end
end
